package yxy.apple.util;

import java.io.File;
import java.io.FileInputStream;
import java.security.MessageDigest;

public class MD5Utility {

	/** 获取文件的md5校验 */
	static public String getMD5(File file) throws Exception {
		FileInputStream fis = new FileInputStream(file);
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			byte[] dataBytes = new byte[1024];

			int nread = 0;
			while ((nread = fis.read(dataBytes)) != -1) {
				md.update(dataBytes, 0, nread);
			}
			byte[] mdbytes = md.digest();
			StringBuffer sb = new StringBuffer();
			for (int i = 0; i < mdbytes.length; i++) {
				sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1));
			}
			return sb.toString();
		} finally {
			fis.close();
		}
	}

	//生成md5串
	public static String MD5(String str) {
		try {
			// 生成一个MD5加密计算摘要
			MessageDigest md = MessageDigest.getInstance("MD5");
			// 进行utf-8编码
			byte[] bs = str.getBytes("utf-8");
			// 计算md5函数
			md.update(bs);
			// digest()最后确定返回md5 hash值，返回值为8为字符串。因为md5 hash值是16位的hex值，实际上就是8位的字符
			// BigInteger函数则将8位的字符串转换成16位hex值，用字符串来表示；得到字符串形式的hash值
			// return new BigInteger(1, md.digest()).toString(16);
			byte[] md5sum = md.digest();

			char[] HEX_DIGITS = "0123456789ABCDEF".toCharArray();
			char[] chars = new char[md5sum.length * 2];
			for (int i = 0; i < md5sum.length; i++) {
				chars[i * 2] = HEX_DIGITS[(md5sum[i] >> 4) & 0xf];
				chars[i * 2 + 1] = HEX_DIGITS[md5sum[i] & 0xf];
			}
			return new String(chars);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
}
